package com.tian.arch.config

import com.tian.arch.function.http.ApiException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 定义的全局异常处理逻辑
 */
typealias ErrorHandlerFactory = (Throwable) -> Unit

/**
 * 以toast提示做的 异常处理器
 */
class ToastErrorHandler : ErrorHandlerFactory {

    companion object {
        val instance by lazy { ToastErrorHandler() }
    }

    override fun invoke(throwable: Throwable) {
        throwable.printStackTrace()
        val msg = when (throwable) {
            is ApiException -> throwable.message
            is ConnectException, is UnknownHostException -> "网络不可用，请检查网络设置"
            is SocketTimeoutException -> "网络请求超时"
            is HttpException -> "服务器繁忙，请稍后再次尝试"
            else -> "出错了，请稍后再试"
        }
        showToast(msg)
    }
}

class IgnoreErrorHandler : ErrorHandlerFactory {

    companion object {
        val instance by lazy { IgnoreErrorHandler() }
    }

    override fun invoke(throwable: Throwable) {
        throwable.printStackTrace()
    }
}